# /usr/bin/env python3.6
# -*- encoding: utf-8 -*-
"""
@File    : utils.py
@Time    : 2020/2/6 0006 13:53
@Author  : zhangbing
@Email   : 18829172841@163.com
@Software: PyCharm
"""
from flask import request, g
from flask_restful import abort

from App.apis.api_constant import USER_CINEMA_PREFIX
from App.ext import cache
from App.models.cinema_admin.model_utils import get_cinema_user


def _verfiy():
    token = request.form.get("token")
    if not token or not token.startswith(USER_CINEMA_PREFIX):
        print (token)
        abort(401, msg="not login")
    user_id = cache.get(token)
    if not user_id:
        abort(401, msg="user not  avaliable")
    user = get_cinema_user(user_id)
    if not user:
        abort(401, msg="请提供有效的令牌")
    g.user = user
    g.auth = token


def login_cinema_required(fun):
    def _wapper(*args, **kwargs):
        _verfiy()
        return fun(*args, **kwargs)

    return _wapper


def required_cinemaaddress_permission(permission):
    def _login_required(fun):
        def _wapper(*args, **kwargs):
            _verfiy()
            if not g.user.check_permssion(permission):
                abort(403, msg="user  can't  access")
            return fun(*args, **kwargs)

        return _wapper

    return _login_required


if __name__ == "__main__":
    pass
